package com.mls.fivedistrict.controller.backend;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.common.RequestHolder;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.pojo.HotWord;
import com.mls.fivedistrict.server.HotWordService;
import com.mls.fivedistrict.util.validator.BeanValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("api/manager")
public class HotWordController {
    @Autowired
    HotWordService hotWordService;

    @GetMapping("/v1/hotWords")
    public ServiceResponse getList() {
        PageFilter pageFilter = RequestHolder.getPageFilter();
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List<HotWord> hotWordList = hotWordService.selectList(pageFilter.getWrapper());
        PageInfo pageInfo = new PageInfo<HotWord>(hotWordList, 5);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    @GetMapping("/v1/hotWord/{hotWordId}")
    public ServiceResponse get(@PathVariable("hotWordId") long hotWordId) {
        HotWord hotWord = hotWordService.selectById(hotWordId);
        return ServiceResponse.createSuccessResponse(hotWord);
    }

    @PutMapping("v1/hotWord/{hotWordId}")
    public ServiceResponse updateById(@PathVariable("hotWordId") long hotWordId, @RequestBody HotWord hotWord) {
        hotWord.setId(hotWordId);
        boolean update = hotWordService.updateById(hotWord);
        if (update) {
            return ServiceResponse.createSuccessResponse("编辑成功");
        }
        return ServiceResponse.createSuccessResponse("编辑失败");
    }

    @PostMapping("v1/hotWord")
    public ServiceResponse add(@RequestBody HotWord hotWord) {
        //1所有的添加操作统一校验
        BeanValidator.check(hotWord);
        boolean insert = hotWordService.insert(hotWord);
        if (insert) {
            return ServiceResponse.createSuccessResponse("添加成功");
        } else {
            return ServiceResponse.createSuccessResponse("添加失败");
        }

    }

    @DeleteMapping("v1/hotWord/{hotWordId}")
    public ServiceResponse deleteById(@PathVariable("hotWordId") Long hotWordId) {
        HotWord hotWord = new HotWord();
        hotWord.setId(hotWordId);
        hotWord.setIsDelete(true);
        boolean insert = hotWordService.updateById(hotWord);
        if (insert) {
            return ServiceResponse.createSuccessResponse("删除成功");
        }
        return ServiceResponse.createErrorResponse("删除失败");
    }

}
